package thinking_net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ChatClient extends Thread {

	private int id;
	private DatagramSocket s;
	private InetAddress hostAddress;
	private byte[] buf=new byte[1000];
	private DatagramPacket dp=new DatagramPacket(buf, buf.length);

	public ChatClient(int identifer) {
		this.id = identifer;
		try {
			s = new DatagramSocket();
			hostAddress = InetAddress.getByName("localhost");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		for (int i = 0; i < 2; i++) {
			
			String outMessage="client again id:"+id+"   message#"+i;
			try {
				s.send(Dgram.toDatagram(outMessage, hostAddress, ChatServer.PORT));
				
				s.receive(dp);
				
				String receiver=new String(dp.getData())+dp.getAddress()+dp.getPort();
				System.out.println(receiver);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 2; i++) {
			new ChatClient(i).start();
			
		}
	}
}
